<template>
  <q-page class="q-pa-md">
    <div style="position: relative; user-select: none;" v-loading="loading">
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <q-breadcrumbs-el label="训练任务" icon="bi-folder2-open" />
        <q-breadcrumbs-el label="数据集配置" icon="bi-people" />
      </q-breadcrumbs>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="130px" class="demo-ruleForm typeBox"
        style="max-width: 50%;" status-icon>
        <el-form-item label="训练特征集：" prop="featureset_id">
          <el-select v-model="ruleForm.featureset_id" class="m-2" placeholder="请选择特征集名称" v-load-more="getMoreData">
            <el-option v-for="item in allAlg.results" :key="item.title" :label="item.title" :value="item.id" />
            <div v-if="loadingMoreState" class="selectMoreData">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>加载更多
            </div>
          </el-select>
        </el-form-item>
        <q-breadcrumbs class="q-mb-md" active-color="#333333"
          style="height:40px;line-height: 40px; border-bottom: 1px dashed #ccc;width: 100%;position: absolute;">
          <q-breadcrumbs-el label="训练任务" />
          <q-breadcrumbs-el label="资源配置" />
        </q-breadcrumbs>
        <el-form-item label="训练资源：" class="cpuDataBox" style="margin-top: 90px;">
          <template #default>
            <div class="title" style="min-width: 500px;">允许使用的最大cpu核数为32核，内存最大为128G</div>
            <div class="row" style="min-width: 500px;">
              <div class="col">
                CPU核数：<el-input class="numberInput"
                  oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>32)value=32;if(value<=0)value=null"
                  type="number" v-model="ruleForm.cpu" size="small" style="width: 60px;"></el-input> 核
              </div>
              <div class="col" style="margin-right: -30px;">
                内存：<el-input class="numberInput"
                  oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>131072)value=131072;if(value<=0)value=null"
                  v-model="ruleForm.memory" size="small" style="width: 60px;"></el-input> M
              </div>
              <div class="col">
                GPU卡数：<el-input class="numberInput" v-model="ruleForm.gpu" size="small" style="width: 60px;"></el-input> 核
              </div>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="自动停止：">
          <template #default>
            <div>
              <el-switch v-model="ruleForm.is_auto_stop" />
              <transition name="el-zoom-in-top">
                <div class="colorBox" v-show="ruleForm.is_auto_stop">
                  时长：<el-input v-model="stop_in_seconds" size="small" @input="inputChange" style="width: 60px;"></el-input> 小时
                  <i>作业时间到最大值会强制停止，若训练未完成可能会造成作业失败</i>
                </div>
              </transition>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="故障自动重启：">
          <template #default>
            <div>
              <el-switch v-model="ruleForm.is_fail_restart" />
              <transition name="el-zoom-in-top">
                <div class="colorBox" v-show="ruleForm.is_fail_restart">
                  重启次数： <el-select v-model="ruleForm.restartNum" class="m-2" placeholder="" size="small"
                    style="width: 60px;">
                    <el-option :label="1" :value="1" />
                    <el-option :label="2" :value="2" />
                    <el-option :label="3" :value="3" />
                  </el-select><i>设置后无法更改</i>
                </div>
              </transition>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="清除缓存：">
          <el-switch v-model="ruleForm.is_clear_conda_cache " />
          <el-tooltip class="box-item" effect="light " content="清除数据缓存" placement="right-start">
            <el-button
              style="transform: scale(.8);transform-origin:left ; margin:0 0 0 5px; font-size: 18px;color: #333;border-color: #333;"
              size="small" circle>?
            </el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <div class="row" style="position:absolute;right: 50px;bottom:-20px">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交训练
        </el-button>
      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, reactive, shallowRef, Directive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import { createRuns } from 'src/api/model'
import { getFeatureset } from 'src/api/dataset'
import { modelStore } from 'src/stores/model'
import { ElMessageBox } from 'element-plus'
import vLoadMore from 'src/utils/loadMore'
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const stop_in_seconds=ref(0.5)
const ruleForm = reactive({
  is_auto_stop: false,
  stop_in_seconds: 0.5,
  is_fail_restart: false,
  restartNum: 1,
  cpu: 1,
  gpu: 1,
  memory: 100,
  featureset_id: '',
  is_clear_conda_cache: false
})
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '算法名称不能为空', trigger: 'blur' }
  ],
  cpu: [
    { required: true, message: '输入核心数', trigger: 'blur' }
  ],
  featureset_id: [
    { required: true, message: '请选择数据集' }
  ],

})
const allAlg = reactive({
  count: 0,
  results: <any>[]
})
const pageData = ref({
  page: 1
})
const loadingMoreState = ref(false)

const submitForm = async (formEl: FormInstance | undefined) => {
  ruleForm.stop_in_seconds= stop_in_seconds.value*60*60
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let piniaObj = modelStore().createModelObj
      delete piniaObj.modelId
      delete piniaObj.sources
      let submitObj = Object.assign(ruleForm, modelStore().createModelObj)
      let modeId = modelStore().model_id
      createRuns(projectId, modeId, submitObj).then((res) => {
        ElMessageBox.alert('新增训练任务完成', '提示', {
          confirmButtonText: '知道了',
          autofocus: false
        }).then(() => {
          router.push({ name: 'model-manage', params: { project_id: projectId } })
        })
      }).finally(() => {
        console.log('success')
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'model-manage', params: { project_id: projectId } })
}
chooseFeatureset()
function chooseFeatureset() {
  loading.value = false
  getFeatureset(projectId, pageData.value).then((res: any) => {
    allAlg.count = res.data.count
    if (allAlg.results.length == 0) {
      allAlg.results = res.data.results
    } else {
      allAlg.results = allAlg.results.concat(res.data.results)
    }
    loadingMoreState.value = false
  }).catch(error => {
    console.log(error)
  })
}
function inputChange(){
  stop_in_seconds.value=(stop_in_seconds.value).replace(/[^0-9.]/g, '')
}
// 下拉懒加载
const getMoreData = async () => {
  if (pageData.value.page < (allAlg.count) / 10) {
    loadingMoreState.value = true
    pageData.value.page++
    chooseFeatureset()
  }
}
</script>

<style scoped lang="scss">
.borderBox {
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #cccccc;
  border-bottom: none;
  padding: 0 5px;
  word-break: break-all;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;

  &:first-child {
    border-radius: 4px 4px 0 0;
  }

  &:last-child {
    border-bottom: 1px solid #cccccc;
    border-radius: 0 0 4px 4px;
  }
}

.rightBox {
  text-align: left;
}

.cpuDataBox {
  color: #585858;

  .title {
    font-size: 12px;
    color: #666;
  }
}

.colorBox {
  color: #585858;

  i {
    display: inline-block;
    font-size: 12px;
    font-style: initial;
    margin-left: 5px;
    transform: scale(0.9);
    transform-origin: left bottom;

  }
}

.numberInput {

  &::v-deep input::-webkit-outer-spin-button,
  &::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }

  &::v-deep input[type='number'] {
    -moz-appearance: textfield !important;
  }
}

.selectMoreData {
  text-align: center;
  padding: 5px 0;
  border-top: 1px solid #f6f6f6;
  color: #aaa;

  .el-icon {
    vertical-align: middle;
    margin: -2px 2px 0 0;
    font-size: 16px;
  }
}
</style>
